<template>
  <div class="uni-scroll app-container" style="height: calc(100vh - 100px)">
    <!--    <el-alert-->
    <!--      v-show="!loading"-->
    <!--      :title="$t('OFFLINE')"-->
    <!--      type="error"-->
    <!--    />-->
    <el-button @click="deviceMonitor">{{ $t('curve') }}</el-button>
    <div ref="countChart" style="width: 100%;height: 1200px"/>
  </div>
</template>

<script>
import { detailsDevice } from '@/api/iot/iotDeviceApi'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import { listCameraBind } from '@/api/camera/cameraBindApi'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'
import { formatDeviceStatus, formatLocationType } from '@/util/common'
import * as echarts from 'echarts'
import resize from '@/components/Mixins/resize'

export default {
  mixins: [resize],
  name: 'DeviceInfo',
  data() {
    return {
      // loading: false,
      chart: null,
      deviceCore: '',
      deviceName: '',
      device: {},
      cameraList: [],
      sensorList: [],
      wsMonitor: {
        room: 'iot:device:' + this.deviceCore,
        onmessage: this.onSocketMsg
      }
    }
  },
  beforeDestroy() {
    // if (this.chart) {
    //   this.chart.dispose()
    //   this.chart = null
    // }
    // if (this.ws == null) {
    //   return
    // }
    // this.ws.send(JSON.stringify({
    //   cmd: 'unBindRoom',
    //   param: 'iot:device:' + this.deviceCore
    // }))
    this.closeSocket()
  },
  mounted() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    detailsDevice({
      deviceCore: this.deviceCore
    }).then(res => {
      const { data, code } = res
      if (code === '200') {
        this.device = data
        // this.initSocket()
        this.listSensorWith()
      }
    })
    this.wsMonitor.room = 'iot:device:' + this.deviceCore
    listenWebSocket(this.wsMonitor)
  },
  methods: {
    formatLocationType(locationType) {
      return formatLocationType(this, locationType)
    },
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
      // this.loading = false
      // if (this.ws) {
      //   this.ws.onclose = null
      //   this.ws.close()
      //   this.ws = null
      // }
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'deviceData') {
        const data = JSON.parse(nowData.msg)
        if (data.deviceUpload) {
          this.listSensorWith()
        }
      }
    },
    // initSocket() {
    //   const that = this
    //   const token = getToken()
    //   if (!token || token === '' || token === 'null') {
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //     return
    //   }
    //   this.closeSocket()
    //   this.ws = newWebSocket()
    //   this.ws.onopen = () => {
    //     that.loading = true
    //     that.ws.send(JSON.stringify({
    //       cmd: 'bindRoom',
    //       param: 'iot:device:' + that.deviceCore
    //     }))
    //   }
    //   this.ws.onerror = function(e) {
    //     console.log('WebSocket is error' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     that.closeSocket()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onclose = function(e) {
    //     console.log('WebSocket is close' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     that.closeSocket()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onmessage = function(msg) {
    //     const nowData = JSON.parse(msg.data)
    //     if (nowData.type === 'deviceData') {
    //       const data = JSON.parse(nowData.msg)
    //       if (data.deviceUpload) {
    //         that.listSensorWith()
    //       }
    //     }
    //   }
    // },
    deviceMonitor() {
      this.$router.push({
        path: '/device/monitor/' + this.deviceCore,
        query: { deviceCore: this.deviceCore, deviceName: this.deviceName }
      })
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withExplain: true,
        withParam: true,
        withSetting: true
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.sensorList = data
          this.listCameraBind()
        }
      })
    },
    listCameraBind() {
      listCameraBind({
        deviceCore: this.deviceCore
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.cameraList = data
        }
        this.showChart()
      })
    },
    showChart() {
      const data = {
        'name': this.deviceName,
        'children': [
          this.makeSensor(this.sensorList),
          this.makeCamera(this.cameraList),
          this.makeInfo(this.device)
        ]
      }
      this.initChart(data)
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    makeSetting(settingList) {
      const data = {
        'name': this.$t('setting'),
        'children': []
      }
      if (settingList.length > 0) {
        settingList.forEach(setting => {
          const settingTree = {
            'children': [],
            'name': setting.name
          }
          switch (setting.type) {
            case 'fixedParam':
              setting.paramList.forEach(param => {
                if (param.value === setting.value) {
                  settingTree['name'] = setting.name + '[' + param.name + ']'
                  return
                }
              })
              break
            case 'noParam':
              settingTree['name'] = setting.name
              break
            case 'switch':
              if (setting.value === '1') {
                settingTree['name'] = setting.name + '[' + this.$t('open') + ']'
              } else {
                settingTree['name'] = setting.name + '[' + this.$t('close') + ']'
              }
              break
            default:
              settingTree['name'] = setting.name + '[' + setting.value + setting.unit + ']'
              break
          }
          if (setting.paramList) {
            setting.paramList.forEach(param => {
              settingTree['children'].push(
                { 'name': param.name + ': ' + param.value, 'value': param.value }
              )
            })
          }
          data['children'].push(settingTree)
        })
      }
      return data
    }, makeSensor(sensorList) {
      const data = {
        'name': this.$t('sensor'),
        'children': []
      }
      if (sensorList.length > 0) {
        sensorList.forEach(sensor => {
          const sensorTree = {
            'name': sensor.sensorName,
            'children': [this.makeExplain(sensor.explainList), this.makeSetting(sensor.settingList), this.makeParam(sensor.paramList)]
          }
          data['children'].push(sensorTree)
        })
      }
      return data
    },
    makeExplain(explainList) {
      const data = {
        'name': this.$t('explain'),
        'children': []
      }
      if (explainList.length > 0) {
        explainList.forEach(explain => {
          data['children'].push(
            { 'name': explain.name + ': ' + explain.value + explain.unit, 'value': explain.value }
          )
        })
      }
      return data
    },
    makeParam(paramList) {
      const data = {
        'name': this.$t('param'),
        'children': []
      }
      if (paramList.length > 0) {
        paramList.forEach(param => {
          data['children'].push(
            { 'name': param.name + ': ' + param.value, 'value': param.value }
          )
        })
      }
      return data
    }, makeInfo(device) {
      this.deviceName = device.deviceName
      this.setTagsViewTitle()
      const data = {
        'name': this.$t('info'),
        'children': [
          {
            'name': this.$t('deviceCore'),
            'children': [
              {
                'name': device.deviceCore
              }
            ]
          },
          {
            'name': this.$t('cardNumber'),
            'children': [
              {
                'name': device.phoneNumber
              }
            ]
          },
          {
            'name': this.$t('status'),
            'children': [
              {
                'name': formatDeviceStatus(this, device.status)
              }
            ]
          },
          {
            'name': this.$t('location') + this.$t('type'),
            'children': [
              {
                'name': formatLocationType(this, device.locationType)
              }
            ]
          },
          {
            'name': this.$t('signal'),
            'children': [
              {
                'name': -(113 - 2 * device.netSignal) + 'dBn'
              }
            ]
          },
          {
            'name': this.$t('surplus'),
            'children': [
              {
                'name': device.surplus + '%'
              }
            ]
          },
          {
            'name': this.$t('remark'),
            'children': [
              {
                'name': device.remark
              }
            ]
          },
          {
            'name': this.$t('product'),
            'children': [
              {
                'name': device.product
              }
            ]
          },
          {
            'name': this.$t('series'),
            'children': [
              {
                'name': device.series
              }
            ]
          },
          {
            'name': this.$t('company'),
            'children': [
              {
                'name': device.companyName
              }
            ]
          },
          {
            'name': this.$t('ip'),
            'children': [
              {
                'name': device.clientIp
              }
            ]
          },
          {
            'name': this.$t('hardware') + this.$t('version'),
            'children': [
              {
                'name': device.hardVersion
              }
            ]
          },
          {
            'name': this.$t('softVersion'),
            'children': [
              {
                'name': device.softVersion
              }
            ]
          },
          {
            'name': this.$t('address'),
            'children': [
              {
                'name': device.address
              }
            ]
          }
        ]
      }
      return data
    }, makeCamera(cameraList) {
      const data = {
        'name': this.$t('camera'),
        'children': []
      }
      if (cameraList.length > 0) {
        cameraList.forEach(camera => {
          data['children'].push(
            { 'name': camera.name, 'value': camera.hid }
          )
        })
      }
      return data
    },

    initChart(data) {
      this.chart = echarts.init(this.$refs.countChart)
      this.chart.setOption({
        series: [
          {
            type: 'tree',
            name: this.$t('param'),
            data: [data],
            top: '0',
            left: '150px',
            bottom: '0',
            right: '300px',
            symbolSize: 5,
            initialTreeDepth: 4,
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right'
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      })
    }
  }
}
</script>
